package com.gaohe.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohe.common.R;
import com.gaohe.pojo.SysUser;
import com.gaohe.service.SysUserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author liu
 * @since 2025-04-12
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost")
public class SysUserController {
    @Autowired
    private SysUserService userService;
    /**
     * 管理员登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody SysUser user){
        System.err.println(user);
        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername,user.getUsername());
        SysUser user1 = userService.getOne(queryWrapper);
        //3、如果没有查询到则返回登录失败结果
        if(user1 == null){
            return R.error("登录失败");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if(!user1.getPassword().equals(password)){
            return R.error("登录失败");
        }
        System.err.println(user1);
        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(user1.getStatus() == 0){
            return R.error("账号已禁用");
        }
        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("user",user1.getUserId());
        request.getSession().setMaxInactiveInterval(60*60*60*60);
        System.err.println(request.getSession().getAttribute("user"));
        return R.success(user1);
    }
    @GetMapping("/{id}")
    public R getUserById(@PathVariable("id") Long id){
        System.err.println(id);
        final SysUser sysUserById = userService.getSysUserById(id);
        return R.success(sysUserById);
    }
}

